#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
管理员数据模型
"""

from database import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash

class Admin(db.Model):
    __tablename__ = 'admins'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False, comment='用户名')
    password_hash = db.Column(db.String(255), nullable=False, comment='密码哈希')
    name = db.Column(db.String(100), nullable=False, comment='姓名')
    email = db.Column(db.String(100), unique=True, nullable=True, comment='邮箱')
    phone = db.Column(db.String(20), nullable=True, comment='手机号')
    
    # 权限信息
    role = db.Column(db.String(20), default='admin', comment='角色：super_admin超级管理员，admin管理员，operator操作员')
    permissions = db.Column(db.Text, nullable=True, comment='权限列表（JSON格式）')
    
    # 状态信息
    status = db.Column(db.Integer, default=1, comment='状态：1正常，0禁用')
    last_login_at = db.Column(db.DateTime, nullable=True, comment='最后登录时间')
    last_login_ip = db.Column(db.String(50), nullable=True, comment='最后登录IP')
    
    # 系统字段
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    created_by = db.Column(db.Integer, nullable=True, comment='创建人ID')
    
    def __init__(self, **kwargs):
        super(Admin, self).__init__(**kwargs)
        if 'password' in kwargs:
            self.password = kwargs['password']
    
    @property
    def password(self):
        raise AttributeError('密码不可读')
    
    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)
    
    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)
    
    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'name': self.name,
            'email': self.email,
            'phone': self.phone,
            'role': self.role,
            'permissions': self.permissions,
            'status': self.status,
            'last_login_at': self.last_login_at.isoformat() if self.last_login_at else None,
            'last_login_ip': self.last_login_ip,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'created_by': self.created_by
        }
    
    def __repr__(self):
        return f'<Admin {self.username}>'